//
//  HMEmoticonKeyboard.swift
//  表情键盘
//
//  Created by WGP on 16/4/20.
//  Copyright © 2016年 WGP. All rights reserved.
//

import UIKit

class HMEmoticonKeyboard: UIView {

    private let ReuseIdentifier = "cell"
    
//    表情键盘对应的textView
    weak var textView: UITextView?
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        
        let newFrame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 216)
        super.init(frame: newFrame)
        
        setupUI()
    }
    
    private func setupUI()
    {
        backgroundColor = UIColor.brownColor()
//        1.添加子控件
        
        addSubview(collectionView)
        addSubview(emoticonToolBar)
        addSubview(pageControl)
        
//        2.添加约束
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        emoticonToolBar.translatesAutoresizingMaskIntoConstraints = false
        pageControl.translatesAutoresizingMaskIntoConstraints = false
        
//        VFL
//        collectionView 水平,左右和父控件重合
//         H:水平 V:垂直
//        ||, |:父控件左边/顶部  父控件右边/底部:|
//        [cv]:表示一个View [:view的左边   view的右边:]
//        Views: VFL里面用到的view映射
        
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: [], metrics: nil, views: ["cv":collectionView]))
        
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: [], metrics: nil, views: ["tb":emoticonToolBar]))
        
//        垂直方向
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-[tb(44)]-0-|", options: [], metrics: nil, views: ["cv":collectionView,"tb":emoticonToolBar]))
        
//        pageControl约束
        addConstraint(NSLayoutConstraint(item: pageControl, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: pageControl, attribute: .Bottom, relatedBy: .Equal, toItem: emoticonToolBar, attribute: .Top, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: pageControl, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 25))
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
//        在这个方法里collectionView的大小才确定下来
        layout.itemSize = collectionView.frame.size
    }
    
//    MARK: - 懒加载
    
    private lazy var collectionView: UICollectionView =
    {
        let layout = UICollectionViewFlowLayout()
        
       let cv = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
   
//        配置Layout的一些属性
        layout.scrollDirection = .Horizontal
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        
        cv.backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        cv.pagingEnabled = true
        cv.showsHorizontalScrollIndicator = false
        cv.bounces = false
        
        cv.delegate = self
        cv.dataSource = self
        
//        闭包
        cv.registerClass(HMEmoticonKeyboardCell.self, forCellWithReuseIdentifier: self.ReuseIdentifier)
        
        return cv
    }()
    
    private lazy var emoticonToolBar: HMEmoticonToolBar =
    {
        let toolBar = HMEmoticonToolBar.emoticonToolBar()
        
        toolBar.delegate = self
        
        return toolBar
    }()
    
    private lazy var pageControl: UIPageControl =
    {
        let control = UIPageControl()
        
        control.hidden = true
        
//        设置
        control.numberOfPages = 5
        control.currentPage = 2
        
//       _pageImage 普通的
//        _currentPagrImage 选中的
        control.setValue(UIImage(named: "compose_keyboard_dot_normal"), forKey: "_pageImage")
        control.setValue(UIImage(named: "compose_keyboard_dot_selected"), forKey: "_currentPageImage")
        
        return control
    }()
    

}

//实现代理协议
extension HMEmoticonKeyboard: HMEmoticonToolBarDelegate
{
//    实现按钮点击的代理方法
    func emoticonToolBarBtnDidClicked(emoticonToolBar: HMEmoticonToolBar, selectedBtnType type: HMEmoticonToolBarType) {
        
        let indexPath = NSIndexPath(forItem: 0, inSection: type.rawValue)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
        
        setupPageControl(indexPath)
    }
}

//实现数据远代理
extension HMEmoticonKeyboard: UICollectionViewDataSource,UICollectionViewDelegate
{
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return HMEmoticonManager.sharedManager.packageModels.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return HMEmoticonManager.sharedManager.packageModels[section].pageEmoticons.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ReuseIdentifier, forIndexPath: indexPath) as! HMEmoticonKeyboardCell
        
            
         cell.indexPath = indexPath
        
        cell.pageEmoticon = HMEmoticonManager.sharedManager.packageModels[indexPath.section].pageEmoticons[indexPath.item]
         
        cell.delegate = self
        
        return cell
    }
    
//    scrollView滚动
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        var refPoint = scrollView.center
        refPoint.x += scrollView.contentOffset.x
        
//        下面这两种方法都是可以的
//        collectionView.indexPathForItemAtPoint(refPoint)
        for cell in collectionView.visibleCells()
        {
            if cell.frame.contains(refPoint)
            {
                let indexPath = collectionView.indexPathForCell(cell)
                
                emoticonToolBar.switchSelectdBtn(indexPath!.section)
                
                setupPageControl(indexPath!)
                break
            }
            
        }
    }
    
    private func setupPageControl(indexPath: NSIndexPath)
    {
        pageControl.numberOfPages = HMEmoticonManager.sharedManager.packageModels[indexPath.section].pageEmoticons.count
        pageControl.currentPage = indexPath.item
        
        pageControl.hidden = indexPath.section == 0
    }
}

extension HMEmoticonKeyboard: HMEmoticonKeyboardCellDelegate
{
    func emoticonKeyboardPageCell(cell: HMEmoticonKeyboardCell, didSelectedEmoticon: HMEmoticonModel)
    {
        textView?.insertEmoticon(didSelectedEmoticon)
//        添加到最近表情
        HMEmoticonManager.sharedManager.addRecentEmoticon(didSelectedEmoticon)
    }
    
//    删除按钮被点击了
    func emoticonKeyboardCellDidClickDeleteBtn(cell: HMEmoticonKeyboardCell) {
        
        textView?.deleteBackward()
        
    }
    
    ///将模型的内容添加到textView上面
//    private func insertEmoticon(emoticon: HMEmoticonModel)
//    {
//        //    1.emoji表情
//        if let emoji = emoticon.emoji
//        {
//            textView?.insertText(emoji)
//            return
//        }
//        
//        //    2.图片表情
//        if let png = emoticon.fullPngPath
//        {
//            let attachment = HMTextAttachment()
//            attachment.image = UIImage(named: png)
//            
////            把模型对应的名称发到附件中
//            attachment.chs = emoticon.chs
//            
//            let wh = textView?.font?.lineHeight ?? 15
//            attachment.bounds = CGRect(x: 0, y: -5, width: wh, height: wh)
//            
//            let attrM = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
//            
////            附件没有font属性跟在他后面的图片就会变得很小
//            attrM.addAttribute(NSFontAttributeName, value: textView!.font!, range:NSRange(location: 0, length: 1))
//            
////            将带图片的属性文本,替换现有的文本光标位置
//            let currentText = NSMutableAttributedString(attributedString: textView!.attributedText)
//            
////            当前光标的位置
//            let currentSelectedRange = textView!.selectedRange
//            currentText.replaceCharactersInRange(currentSelectedRange, withAttributedString: attrM)
//            
////            3.textView设置属性文本
//            textView?.attributedText = currentText
//            
////            设置光标的位置
//            textView?.selectedRange = NSRange(location: currentSelectedRange.location + 1, length: 0)
//        }
//    }
}


















